package com.example.imtoken.modules.main.wallet.assets.add

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.BusUtils
import com.blankj.utilcode.util.LogUtils
import com.example.imtoken.core.App
import com.example.imtoken.core.base.BaseViewModel
import com.example.imtoken.core.http.BaseObserver
import com.example.imtoken.core.logic.network.RetrofitUtils
import com.example.imtoken.core.logic.repository.WalletRepository
import com.example.imtoken.core.utils.BusConfig
import com.example.imtoken.entitys.http.Children
import com.example.imtoken.entitys.http.CoinsEntity
import com.example.imtoken.entitys.http.ResponseEntity
import com.example.imtoken.room.base.AppDataBase
import com.example.imtoken.room.schema.WalletAddressSchema
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.launch
import java.util.*

class AddAssetsViewModel(private val repository: WalletRepository) : BaseViewModel() {

    private var dataLiveData: MutableLiveData<MutableList<Children>> = MutableLiveData()

    fun getDataLiveData(): MutableLiveData<MutableList<Children>> {
        return dataLiveData
    }

    fun updateStatus(position: Int) {
        val newData = ArrayList<Children>()
        dataLiveData.value?.let {
            for (data in it) {
                val newItem = data.copy()
                newItem.isSelect = data.isSelect
                newData.add(newItem)
            }
            newData[position].isSelect = !newData[position].isSelect
            if (newData[position].isSelect) insertWalletAddress(newData[position])
            dataLiveData.value = newData
        }
    }

    fun updateStatus(walletType: String) {
        val newData = ArrayList<Children>()
        var position = -1
        dataLiveData.value?.let {
            for (i in 0 until it.size) {
                val newItem = it[i].copy()
                newItem.isSelect = it[i].isSelect
                newData.add(newItem)
                if (newItem.coin == walletType) {
                    position = i
                }
            }
            newData[position].isSelect = !newData[position].isSelect
            dataLiveData.value = newData
        }
    }

    private fun insertWalletAddress(data: Children) {
        val appLogin = AppDataBase.instance.getAppLoginDao().getAppLogin()
        val walletCheckedSchema =
            AppDataBase.instance.getWalletCheckedDao().getCheckedWallet(appLogin.walletAddress)
        val walletAddressSchema =
            WalletAddressSchema(
                data.icon,
                data.coin,
                data.name,
                data.address,
                data.describe,
                walletCheckedSchema?.address
            )

        if (AppDataBase.instance.getWalletAddressDao()
                .insertWalletAddress(walletAddressSchema) > 0
        ) {
            LogUtils.e("添加子货币成功")
            BusUtils.postSticky(BusConfig.update_wallet_address_sticky_assets_fragment)

            viewModelScope.launch {
                App.appCode?.let { code ->
                    try {
                        val account = AppDataBase.instance.getAccountDao().getDefAccount(appLogin.walletAddress)
                        val bindingWallet = repository.bindingWallet(
                            account.address,
                            account.password,
                            data.coin,
                            code,
                            data.address
                        )
                        bindingWallet?.let { LogUtils.json(it) }
                    } catch (e: Exception) {

                    }
                }
            }
        } else {
            LogUtils.e("添加子货币失败")
        }
    }

    fun getCoins(coin: String?) {
        RetrofitUtils.apiService?.coins(coin)
            ?.subscribeOn(Schedulers.io())
            ?.unsubscribeOn(Schedulers.io())
            ?.subscribe(object : BaseObserver<ResponseEntity<CoinsEntity>>() {
                override fun onSuccess(value: ResponseEntity<CoinsEntity>) {
                    if (value.code == 0) {
                        if (value.data?.size ?: 0 > 0) {
                            dataProcessing(value.data?.get(0)?.children)
                        }
                    } else {
                        mErrorStr.postValue(value.msg)
                    }
                }

                override fun onFailed(e: Throwable) {
                    LogUtils.e(e.message)
                }

            })
    }

    /**
     * 数据对比处理
     * @param children MutableList<Children>?
     */
    fun dataProcessing(children: MutableList<Children>?) {
        val appLogin = AppDataBase.instance.getAppLoginDao().getAppLogin()
        val walletCheckedSchema =
            AppDataBase.instance.getWalletCheckedDao().getCheckedWallet(appLogin.walletAddress)
        val walletAddress = AppDataBase.instance.getWalletAddressDao()
            .getAccountWalletAddress(walletCheckedSchema?.address)
        if (children != null && walletAddress != null) {
            for (item in children) {
                for (item2 in walletAddress) {
                    if (item.coin == item2.walletType) {
                        item.isSelect = true
                        break
                    }
                }
            }
            dataLiveData.postValue(children)
        }
    }

}